//
//  CallNotesController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/17.
//  Copyright © 2025 考拉🐨. All rights reserved.
//

import UIKit
import SnapKit
import Reusable
import Localize_Swift

class CallNotesController: BaseViewController {
    
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.backgroundColor = .clear
        // 滚动时隐藏键盘
        scrollView.keyboardDismissMode = .onDrag
        if #available(iOS 11.0, *) {
            scrollView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        view.addSubview(scrollView)
        return scrollView
    }()
    
    private lazy var submitButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("确认并发布".localized(.call), for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.setBackgroundColor(.themeColor, for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        button.addTarget(self, action: #selector(submitAction), for: .touchUpInside)
        button.addRoundedCorners(radius: 22)
        return button
    }()
    
    /// 通话时长
    private lazy var durationView: CallNotesInfoView = {
        CallNotesInfoView.loadFromNib()
    }()
    /// 支付积分
    private lazy var paymentPriceView: CallNotesInfoView = {
        CallNotesInfoView.loadFromNib()
    }()
    /// 翻译人数
    private lazy var translatorsNumView: CallNotesInfoView = {
        CallNotesInfoView.loadFromNib()
    }()
    
    /// 翻译人员列表
    private lazy var translatorsListView: CallNotesTranslatorsNumView = {
        CallNotesTranslatorsNumView.loadFromNib()
    }()
    
    /// 翻译服务时长
    private lazy var translatorsDurationView: CallNotesInfoView = {
        CallNotesInfoView.loadFromNib()
    }()
    /// 翻译服务支付积分
    private lazy var translatorsPaymentView: CallNotesInfoView = {
        CallNotesInfoView.loadFromNib()
    }()
    
    /// 翻译服务评价
    private lazy var translatorsEvaluateView: CallNotesTranslatorsEvaluateView = {
        CallNotesTranslatorsEvaluateView.loadFromNib()
    }()
    
    private var roomId: String
    init(_ roomId: String) {
        self.roomId = roomId
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 统计接口调用次数
    private var count: Int = 0
    
    private var callNotesModel: CallNotesModel = CallNotesModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        initNav()
        initUI()
        updateLanguageAction()
        loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        vhl_interactivePopEnable = false
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        vhl_interactivePopEnable = true
    }
    
    override func updateLanguageAction() {
        
        navigationItem.title = "通话小记".localized(.call)
        submitButton.setTitle("确认并发布".localized(.call), for: .normal)
        
        durationView.titleLabel.text = "通话时长".localized(.call)
        paymentPriceView.titleLabel.text = "通话支付积分".localized(.call)
        translatorsNumView.titleLabel.text = "邀请翻译客服".localized(.call)
        translatorsDurationView.titleLabel.text = "翻译服务时长".localized(.call)
        translatorsPaymentView.titleLabel.text = "翻译服务支付".localized(.call)
    }
}


// MARK: - private
private extension CallNotesController {
    
    func initNav() {
        // 设置初始导航栏透明度
        vhl_navBarBackgroundAlpha = 0
        navigationItem.title = "通话小记".localized(.call)
        // navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIView())
    }
    
    func initUI() {
        view.backgroundColor = UIColor(hex: "F7F7F7")
        
        view.addSubview(submitButton)
        submitButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(44)
            make.bottom.equalToSuperview().offset(-xIphoneBottomSafeHeight - 20)
        }
        
        
        scrollView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(xIphoneNavStatusBarHeight)
            make.bottom.equalTo(submitButton.snp.top).offset(-10)
            
        }
        
        scrollView.addSubview(durationView)
        durationView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview()
            make.width.equalTo(xScreenW - 16*2)
            make.height.equalTo(40)
        }
        
        scrollView.addSubview(paymentPriceView)
        paymentPriceView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalTo(durationView.snp.bottom).offset(16)
            make.width.equalTo(xScreenW - 16*2)
            make.height.equalTo(40)
        }
        
        scrollView.addSubview(translatorsNumView)
        translatorsNumView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalTo(paymentPriceView.snp.bottom).offset(16)
            make.width.equalTo(xScreenW - 16*2)
            make.height.equalTo(40)
        }
        
        translatorsListView.delegate = self
        scrollView.addSubview(translatorsListView)
        translatorsListView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalTo(translatorsNumView.snp.bottom).offset(16)
            make.width.equalTo(xScreenW - 16*2)
        }
        
        scrollView.addSubview(translatorsDurationView)
        translatorsDurationView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalTo(translatorsListView.snp.bottom).offset(16)
            make.width.equalTo(xScreenW - 16*2)
            make.height.equalTo(40)
        }
        
        scrollView.addSubview(translatorsPaymentView)
        translatorsPaymentView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalTo(translatorsDurationView.snp.bottom).offset(16)
            make.width.equalTo(xScreenW - 16*2)
            make.height.equalTo(40)
        }
        
        scrollView.addSubview(translatorsEvaluateView)
        translatorsEvaluateView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalTo(translatorsPaymentView.snp.bottom).offset(16)
            make.width.equalTo(xScreenW)
        }
        
        translatorsListView.isHidden = true
        translatorsDurationView.isHidden = true
        translatorsPaymentView.isHidden = true
        translatorsEvaluateView.isHidden = true
        updateScrollViewContentSize()
    }
    
    func updateScrollViewContentSize() {
        view.layoutIfNeeded()
        if !translatorsEvaluateView.isHidden {
            scrollView.contentSize = CGSizeMake(xScreenW, CGRectGetMaxY(translatorsEvaluateView.frame) + 16)
        } else {
            scrollView.contentSize = CGSizeMake(xScreenW, CGRectGetMaxY(translatorsNumView.frame) + 16)
        }
    }
    
    func loadData() {
        let target = JavaAPI.callNotes(roomId: roomId)
        YLHUD.showLottie()
        YLRequest.request(target) { [self] result in
            switch result {
            case .success(let res):
       
                let dataDictionary = res.dataDictionary
                //                let dataDictionary = """
                //        {
                //            \"roomId\": \"call_1_1741946615021\",
                //            \"callDuration\": \"3\",
                //            \"callTimePrice\": 120,
                //            \"translatorCount\": 2,
                //            \"translatorList\": [{
                //                \"userId\": \"113\",
                //                \"name\": \"阿拉山口翻译员\",
                //                \"nameRu\": \"Переводчик Алашанькоу \",
                //                \"translateDuration\": 1,
                //                \"translatePrice\": \"100\"
                //            }, {
                //                \"userId\": \"1238\",
                //                \"name\": \"新的翻译\",
                //                \"nameRu\": \"Новый перевод \",
                //                \"translateDuration\": 1,
                //                \"translatePrice\": \"200\"
                //            }]
                //        }
                //        """.toDictionary()!
                
                // xLog(dataDictionary as NSDictionary)
                guard let model = JsonUtil.modelFromDictionary(dataDictionary, CallNotesModel.self) else { return }
                if model.roomId.isEmpty {
                    DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1) {
                        self.count += 1
                        if self.count > 2 {
                            YLHUD.hideHUD()
                            self.back()
                            return
                        }
//                        self.loadData()
                    }
                    return
                }
                YLHUD.hideHUD()
                callNotesModel = model
                if let translatorModel = callNotesModel.translatorList.first {
                    // 默认选中第一个翻译员
                    translatorModel.isSelected = true
                }
                showData(model: callNotesModel)
                
            case .failure(let err):
                YLHUD.showHint(.error, err.errMsg)
            }
        }
        
    }
    
    func showData(model: CallNotesModel) {
        durationView.contentLabel.text =  model.callDuration + "分钟".localized(.call)
        let duration = model.callDuration.sg.toInt
        if duration < 60 {
            durationView.contentLabel.text = String(duration) + "分钟".localized(.call)
            
        } else {
            let minutes = duration%60
            let hours = duration/60
            durationView.contentLabel.text = "时分".localizedFormat(arguments: String(hours), String(minutes), name: .call)
        }
        
        paymentPriceView.contentLabel.text = String(model.callTimePrice) + "积分".localized(.call)
        translatorsNumView.contentLabel.text = String(model.translatorCount) + "人".localized(.call)
        translatorsListView.list = model.translatorList
        
        if model.translatorCount == 0 {
            translatorsListView.isHidden = true
            translatorsDurationView.isHidden = true
            translatorsPaymentView.isHidden = true
            translatorsEvaluateView.isHidden = true
            updateScrollViewContentSize()
            return
        }
        
        translatorsListView.isHidden = false
        translatorsDurationView.isHidden = false
        translatorsPaymentView.isHidden = false
        translatorsEvaluateView.isHidden = false
        updateScrollViewContentSize()
        
        if let translatorModel = callNotesModel.translatorList.filter({ $0.isSelected }).first {
            // 选中第一个翻译员
            if translatorModel.translateDuration < 60 {
                translatorsDurationView.contentLabel.text = String(translatorModel.translateDuration) + "分钟".localized(.call)
                
            } else {
                let minutes = translatorModel.translateDuration%60
                let hours = translatorModel.translateDuration/60
                translatorsDurationView.contentLabel.text = "时分".localizedFormat(arguments: hours, minutes, name: .call)
            }
            
            translatorsPaymentView.contentLabel.text = translatorModel.translatePrice + "积分".localized(.call)
            translatorsEvaluateView.model = translatorModel
        }
    }
    
}

// MARK: - 响应事件
private extension CallNotesController {
    @objc func submitAction() {
        
        var list: [[String: Any]] = []
        
        if callNotesModel.translatorList.count > 0 {
            for translatorModel in callNotesModel.translatorList {
                // 被选中的数量
                let selectedModels = translatorModel.ratingList.filter { $0.isSelected }
                if selectedModels.count == 0 {
                    YLHUD.showMessage("请对翻译员《》进行评价".localizedFormat(arguments: LanguageManager.isLanguageZH ? translatorModel.name: translatorModel.nameRu, name: .call))
                    return
                }
                
                let evaluates = selectedModels.map { uiModel in
                    return uiModel.title
                }
                xLog("evaluates \(evaluates)")
                let dic: [String: Any] = [
                    "roomId": callNotesModel.roomId,
                    "translatorUserId": translatorModel.userId,
                    "translationDuration": translatorModel.translateDuration,
                    "translationPrice": translatorModel.translatePrice,
                    "level": translatorModel.rating,
                    "comment": evaluates.joined(separator: ",")
                ]
                
                list.append(dic)
            }
        }
        xLog("都评价了，可以发布了")
        
        let target = JavaAPI.saveCallNotes(parameDic: [
            "roomId": callNotesModel.roomId,
            "userId": UserProfile.userId,
            "callDuration": callNotesModel.callDuration,
            "callTimePrice": callNotesModel.callTimePrice,
            "translatorCount": callNotesModel.translatorCount,
            "list": list
        ])
        YLHUD.showLottie()
        YLRequest.request(target) { result in
            switch result {
            case .success(_):
                YLHUD.hideHUD()
                self.dismiss(animated: true, completion: nil)
                
            case .failure(let err):
                YLHUD.showHint(.error, err.errMsg)
            }
        }
    }
}

extension CallNotesController: CallNotesTranslatorsNumViewDelegate {
    func didSelectedItem(model: CallNotesTranslatorModel) {
        showData(model: callNotesModel)
    }
}
